using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteECSWeb;
/// <summary>
/// Summary description for FixReturnUrlRewrite
/// </summary>
namespace SiteECSWeb
{
    public class FixReturnUrlRewrite : IHttpModule
    {
        public FixReturnUrlRewrite()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(app_BeginRequest);
        }

        void app_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            if (context.Request.ServerVariables["HTTP_REFERER"] != null)
            {
                string url = context.Request.ServerVariables["HTTP_REFERER"].ToString();
                int iReturnURL = url.IndexOf("ReturnUrl");
                if (iReturnURL != -1 &&
                    context.Items["UrlRewritingNet.UrlRewriter.ClientQueryString"] != string.Empty)
                {
                    try
                    {
                        string vUrl =
                            context.Items["UrlRewritingNet.UrlRewriter.VirtualUrl"].ToString();
                        string vQs = context.Items["UrlRewritingNet.UrlRewriter.ClientQueryString"].ToString();
                        string newUrl = vUrl.Replace("?" + vQs, "");
                        context.Response.Redirect(newUrl);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }

        #endregion
    }
}
